package yl.hs.bmipfull.controllers.poundroom;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import yl.hs.bmipfull.controllers.ControllerBase;
import yl.hs.bmipfull.service.production.IProductionLineService;
import yl.hs.bmipfull.service.production.ITransTaskService;
import yl.hs.bmipfull.service.vehiclemanage.ITruckInfoService;
import yl.hs.bmipfull.utils.CK;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.WebResult;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.*;

/**
 * 作用:   <br/>
 * 创建时间: 2022-04-11 09:46 <br/>
 *
 * @author 吴高丰
 */
@Api(value = "大屏Web接口", tags = "大屏管理——大屏操作")
@RequestMapping(value = "/largescale/")
@RestController
public class LargeScaleController extends ControllerBase {
    @Value("${photos.url}")
    private String photos;
    @Value("${files.url}")
    private String fileLoadPath;
    @Autowired
    ITruckInfoService servicecar;
    @Autowired
    ITransTaskService transTaskService;
    @Autowired
    IProductionLineService lineService;
    @ApiOperation(value = "查询生产线信息表", notes = "查询生产线信息表")
    @RequestMapping(value = "/getcarbystate", method = RequestMethod.GET)
    public WebResult GetCarByState() {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("state", 10);
            map.put("useType", "mixTruck");
            map.put("sortKey", "sortCode");
            var result = servicecar.queryList(new PageQuery(map));
            return  success("查询成功",result);
        } catch (Exception e) {
            return error(e);
        }
    }
    @ApiOperation(value = "查询生产线信息表", notes = "查询生产线信息表")
    @RequestMapping(value = "/getcarbyLine", method = RequestMethod.GET)
    public WebResult GetCarByLine() {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("state", 20);
            map.put("useType", "mixTruck");
            var result = servicecar.queryList(new PageQuery(map));
            List<Object> data = new ArrayList<>();
            if(result.size()>0) {
                result.forEach(s -> {
                    var mapentity = s.toMap();
                    var protask = transTaskService.queryListByTaskCar(s.getTruckCode()).get(0);
                    var line = lineService.findBySn(protask.getProductionLineSN());
                    mapentity.put("ProLine", line.getPlName());
                    mapentity.put("dispatchTime", protask.getDispatchTime());
                    data.add(mapentity);
                });
            }
            return  success("查询成功",data);
        } catch (Exception e) {
            return error(e);
        }
    }
    /**
     * 文件的上传
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
    public WebResult upload(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        // 判断文件是否为空
        String path = fileLoadPath;
        HashMap<String, String> message = new HashMap<>();
        if (!file.isEmpty()) {
            try {
                // 文件保存路径
//                String filePath = path + "/" + file.getOriginalFilename();
                String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));      //获取文件的后缀名

                String fileName=UUID.randomUUID().toString().replace("-","")+suffixName;
                String filePath = path + File.separator + fileName;        //拼接
                if (!new File(filePath).exists()){
                    new File(filePath).mkdirs();
                }
                // 转存文件
                file.transferTo(new File(filePath));
                message.put("status", filePath);
                return success("文件上传 success!",fileName);
            } catch (Exception e) {
                return error(e);
            }
        }
        return error("失败");
    }

    @PostMapping("/upload")
    public WebResult insertOrderImg(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        // 返回Map
        Map<String, Object> resultMap = new HashMap<>();
        // 文件上传路径
        String location = photos; //TODO 改为服务器路径

        if (!file.isEmpty()) {
            // 获取文件原始名称 a.png -> a
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀 .png
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));

            //设置允许上传文件类型
            String suffixList = ".jpg,.png,.ico,.bmp,.jpeg";
            // 判断是否包含
            if (suffixList.contains(extName.trim().toLowerCase())) {
                // 保存文件的路径
                String fileName = UUID.randomUUID() + extName;
                String path = location  + fileName;

                // 查看路径是否存在，不存在就创建
                //image/jpeg
                if (!new File(path).exists()) {
                    boolean mkdirs = new File(path).mkdirs();
                }
                //  spring的transferTo保存文件方法
                try {
                    file.transferTo(new File(path));
                } catch (IOException e) {
                    return error(e);
                }
                String imgUrl = fileName;
                return success("图片上传 success!",imgUrl);
            }
        } else {
            return error("未选择图片");
        }
        return error("ee");
    }
}
